from system.action import Action

class FrameRate(Action):
    def run(self, args):
        self.lastTime = None
        self.dtimeCache = []
        self.measureTime = args.get('measureTime',1)
    
    def receive_update(self, args):
        time = args['time']
        if not self.lastTime:
            self.lastTime = time
        else:
            dtime = time - self.lastTime
            self.lastTime = time
            self.dtimeCache.insert(0,dtime)
            while sum(self.dtimeCache) > self.measureTime and self.dtimeCache:
                self.dtimeCache.pop()
            if self.dtimeCache:
                fps = float(len(self.dtimeCache)) / sum(self.dtimeCache)
                self.object.setVar("text","fps: %.1f" % fps)
